import { Component } from 'react';

import { Toast, Boxs } from 'saltui';
import { UploadCore, Events, Status, VERSION } from 'uploadcore';

import 'whatwg-fetch';
import 'es6-promise';
const { HBox, Box } = Boxs;
export default class PageHome extends Component {


  constructor(props) {
    super(props);
    var label = props.label;
    if(!label){
      label = '';
    }
    const keyNum = this.GenNonDuplicateID(8);
    // 上传个数限制
    var limitNo = props.limitNo;
    if( limitNo && limitNo>0){
      limitNo = limitNo;
    }else{
      limitNo = 9;
    }

    var setting = getSysAttachSetting();
     // 上传类型images:图片,audios:附件,videos:视频
    var uploadType = props.uploadType;
     // 上传格式
    var extensions = props.extensions;
    if(!extensions){//如果组件没有设置则取后台默认
        extensions = setting.sysAttachmentCate;
    }
    // 可上传
    var canAdd = props.canAdd;
    // 可删除
    var canDel = props.canDel;
    //预览类型，view：永中预览，download：下载
    var viewType = props.viewType;
    if(typeof(viewType) == 'undefined' || viewType == null || viewType == ''){
      viewType = 'view';
    }
    if(setting.sysAttachmentView == 0){//如果设置中预览关闭则默认下载
      viewType = "download";
    }

    //是否必填
    var required = props.required;

    //初始化List
    var initList = props.initList;
    if(typeof(initList) == 'undefined' || initList == null || !(initList instanceof Array)){//判断初始化id集合有没有
      initList = [];
    }


    // 文件大小限制，默认单位byte，默认0，表示不限制
    var fileSizeLimit = props.fileSizeLimit;
    if (fileSizeLimit == null || fileSizeLimit == '' || fileSizeLimit == undefined || fileSizeLimit == 'undefined') {
      //fileSizeLimit = 0;
      //如果组件没有设置则取后台默认
      fileSizeLimit = setting.sysAttachmentSize;
    }
    fileSizeLimit = parseInt(fileSizeLimit);

    //文件总大小限制
    var fileAllSizeLimit = props.fileAllSizeLimit;
    if (fileAllSizeLimit == null || fileAllSizeLimit == '' || fileAllSizeLimit == undefined || fileAllSizeLimit == 'undefined') {
      fileAllSizeLimit = 0;
    }

    var accept = {};
    if(uploadType == 'image'){//图片
      accept = {
        title: '图片',
        extensions: 'jpg,jpeg,png,gif,webp,bmp',
        mimeTypes: 'image/*' // or 'image/jpeg,image/png'
      };
      if(extensions){
        accept.extensions = extensions;
      }
    }else{
      uploadType = "file";
      if(loginUserInfo.thirdMenuType=='MH'){
        accept = null;
      }else{
        if(extensions){
          accept.title = '文件';
          accept.extensions = extensions;
        }else{
          accept = null;
        }
       }
    }
    
    var dir = props.dir;
    var context = document.getElementById("context").value;
    var token = document.getElementById("token").value;
    this.state = {
      required:required,
      canAdd:canAdd,
      canDel:canDel,
      keyNum:keyNum,
      uploadType:uploadType,
      accept:accept,
      fileSizeLimit:fileSizeLimit*1024*1024,
      fileAllSizeLimit:fileAllSizeLimit,
      label: label,
      dir: dir,
      limitNo: limitNo,
      context: context,
      canViewUrl: context + '/api/m/plugin/attachment/mobile/checkViewAttachmentByCode',
      uploadUrl: context + '/api/m/plugin/attachment/mobile/createFile',
      urlPrev: context + '/api/m/plugin/attachment/mobile/viewImage?fid=',
      queryUrl: context + '/api/m/plugin/attachment/mobile/getAttachmentByIds?ids=',
      //queryUrl: context + '/client/approve/getCanBackActivity?ids=',
      token:token,
      canView: true,
      isInit:false,
      addQueNum:0,
      viewType:viewType,
      initList:initList
    };
  }

  GenNonDuplicateID(randomLength){
    return Number(Math.random().toString().substr(3,randomLength) + Date.now()).toString(36)
   }

  del(delIndex) {
    var initList = this.props.initList;
    initList.splice(delIndex, 1);
    this.props.onChange(initList);
  }



  componentDidMount() {
    let t = this;
    var param = {
      name: 'file',
      url:this.state.uploadUrl,
      autoPending: true,
      accept: t.state.accept,
      multiple: true,
      fileSizeLimit:t.state.fileSizeLimit
    };
    let limitNo = t.state.limitNo;
    //param.queueCapcity= limitNo;
    var up = this.getCore(param);
    const picker = up.getPickerCollector();
    picker.addArea(document.getElementById('ddUploadPic' + t.state.keyNum));
  }

  getCore(param){
    const t = this;
    const up = new UploadCore(param);
    up
    .on(Events.FILE_UPLOAD_PREPARING, (request) => {
        request.setHeader("Authorization", "Bearer "+t.state.token);
        request.setParam('dir', t.state.dir);
        console.info(request.getParam('token'));
      })
      .on(Events.QUEUE_FILE_ADDED, (file) => {
      // return false;
          //判断总文件大小不超过
          var fileAllSizeLimit = t.state.fileAllSizeLimit;
          if(fileAllSizeLimit>0){
            let fileAllSize = 0;
            t.state.initList.map(function(item){
              if(item.fileSize == null){
                fileAllSize += item.size;
              }else{
                fileAllSize += item.fileSize;
              }
            });
            if(fileAllSizeLimit*1024*1024<=(fileAllSize+file.size)){
              file.cancel();
              Toast.show({
                type: 'error',
                content: '文件总大小不能超过'+fileAllSizeLimit+'M！',
              });
              return false;
            }
          }
          console.info('queuefileadded', file);
          file.session().progress((e) => {
            console.info('progress', e);
          }).fail((error) => {
            console.info(error)
          }).done((response) => {
            console.info(response.getJson())
          });
        
      })
      .on(Events.FILE_UPLOAD_ERROR, (error) => {
        if(error.name=='AbortError'){//网络中断
          Toast.show({
            type: 'error',
            content: '网络中断！',
          });
          return false;
        }else if(error.name=='TimeoutError'){//网络超时
          Toast.show({
            type: 'error',
            content: '网络中断！',
          });
          return false;
        }else if(error.name=='NetworkError'){//网络错误
          Toast.show({
            type: 'error',
            content: '网络错误！',
          });
          return false;
        }else{
          Toast.show({
            type: 'error',
            content: '上传失败！',
          });
          return false;
        }
      })
      .on(Events.QUEUE_ERROR, (error) => {
        var accept = t.state.accept;
        var fileSizeLimit = t.state.fileSizeLimit;
        if(error.name=='FilterError'){//过滤文件报错
          if(accept){//扩展名出错
            var extensions = accept.extensions;
            if(extensions.indexOf(error.file.ext)<0){
              Toast.show({
                type: 'error',
                content: '不允许上传该后缀名的文件',
              });
              return false;
            }
          }
          
          if(fileSizeLimit>0){
            if(error.file.size>fileSizeLimit){
              var fileSizeLimitName = t.calculate(fileSizeLimit);
              Toast.show({
                type: 'error',
                content: '文件大小不得超过'+fileSizeLimitName,
              });
              return false;
            }
          }

          Toast.show({
            type: 'error',
            content: '文件不能重复！',
          });
          return false;
          
        }else if(error.name=='QueueLimitError'){//队列限制
          Toast.show({
            type: 'error',
            content: '不允许上传更多的文件了！',
          });
          return false;
        }else{
          Toast.show({
            type: 'error',
            content: '上传失败！',
          });
          return false;
        }
      }) 
      .on(Events.FILE_UPLOAD_COMPLETED, (file) => {
        if (file.getStatus() === Status.SUCCESS) {
          //alert('上传成功');
          var result = file.response.getJson();
          if (result.code == -1) {
            alert(result.message);
          } else {
           var json = file.response.getJson().data;
          
            //var checksum = json[0].checksum;
            var initList = t.state.initList;
            if(initList.length < this.state.limitNo){
              initList = initList.concat(json);
              t.props.onChange(initList);
              t.setState({
                initList:initList
              });
            }else{
              Toast.show({
                type: 'error',
                content: '不允许上传更多的文件了！',
              });
              return false;
            }
          }

        } else {
          //file.cancel();
          // var json = [ {
          //   "fileName" : "d33087332a6c477a806d823209fef5c7.png",
          //   "previewUrl" : null,
          //   "fileDisplayName" : "1511353597(1).png",
          //   "downloadUrl" : "/attachment/download?fid=402887dc630ba7e701630bb4fe8f0011&chksum=04c8e2fdbb7ec02bc3492f9c98fa8e36",
          //   "imageSmallerUrl" : "/attachment/dingding/201804/d33087332a6c477a806d823209fef5c7_sm.png",
          //   "imageMiddleUrl" : "/attachment/dingding/201804/d33087332a6c477a806d823209fef5c7_mid.png",
          //   "fileExt" : ".png",
          //   "delFlag" : "0",
          //   "fileModule" : null,
          //   "multiCorpId" : false,
          //   "previewDate" : null,
          //   "imediaUrl" : "/attachment/dingding/201804/d33087332a6c477a806d823209fef5c7.png",
          //   "fileSize" : 67577,
          //   "fileDisplayNameNoExt" : "1511353597(1)",
          //   "relativePath" : "dingding/201804",
          //   "isEncrypted" : 0,
          //   "imageUrl" : "/attachment/image?fid=402887dc630ba7e701630bb4fe8f0011&chksum=04c8e2fdbb7ec02bc3492f9c98fa8e36",
          //   "checksum" : "04c8e2fdbb7ec02bc3492f9c98fa8e36",
          //   "deleteUrl" : "/attachment/delete?fid=402887dc630ba7e701630bb4fe8f0011&chksum=ef9f55278b3594f3eaefef23feacaa7d",
          //   "id" : "402887dc630ba7e701630bb4fe8f0011",
          //   "contentType" : null
          // } ];
          // var img = json;
          // //var checksum = json[0].checksum;
          // var initList = t.props.initList;
          // if(initList.length < this.state.limitNo){
          //   initList = initList.concat(json);

          //   t.props.onChange(initList);
          // }else{
          //   Toast.show({
          //     type: 'error',
          //     content: '不允许上传更多文件了！',
          //   });
          //   return false;
          // }
         
          Toast.show({
            type: 'error',
            content: '上传失败！',
          });
          return false;
        }
      });
      return up;
  }
    //计算大小
    calculate(no){
    let a = no/1024;
    if(a<1){
      return no+'B';
    }
    let b = a/1024;
    if(b<1){
      return Math.round(a*100)/100+'K';
    }
    return Math.round(b*100)/100+'M';
  }

  checkCanView(){
    var t = this;
    //判断可有权限查看附件
    $.ajax({
      url : t.state.canViewUrl+'?token='+t.state.token,
      type : 'GET',
      success : function(data, status, xhr) {
        //{"type":"success","code":"0","message":"操作成功","data":{"isCanView":false}}
        if(data!=null && data.code == '0'){
          t.setState({
            canView:data.data.isCanView
          });
        }else{
          t.setState({
            canView: false
          });
        } 
      },
      error : function(xhr, errorType, error) { 
        console.log("error:" + errorType + ', ' + error);
      }
    }); 
  }

  //预览
  view(file){  
    var id = file.id;
    if(this.state.viewType == 'view'){
      if(this.state.canView){
        var fileExt = file.fileExt;
        downloadFile(id,'android',fileExt);
      }else{
        Toast.show({
          type: 'error',
          content: '您没有移动端查看附件的权限，请联系系统管理员！',
        });
      }
    }else{
      downloadFile(id);
    }
  }

  //初始化ids
  initData(){
    let t = this;
    var initIds = this.props.initIds;
    var initList = [];
    if(typeof(initIds) == 'undefined' || initIds == null || initIds == ''){//判断初始化附件id字符串有没有
      initList = this.props.initList;
      if(typeof(initList) == 'undefined' || initList == null || !(initList instanceof Array)){//判断初始化id集合有没有
        initList = [];
      }
      t.setState({
        initList:initList
      });
    }else{
      //let formData = new FormData();
      //formData.append('token', t.state.token);
      fetch(t.state.queryUrl+initIds,{
        method: "POST",
        headers:{
　　　　    'Content-Type': 'application/x-www-form-urlencoded',
        },
        body:'token='+t.state.token,
        // headers: {
        //     "Content-Type": "application/x-www-form-urlencoded",
        //     "Authorization": "Bearer "+t.state.token,
        //     "Cookie":"epname=zhaoyh; isRemembered=1; epsid=89f2b25f-7719-4b62-8df5-d11303112f4f; eptoken=emhhb3lofDBjOTdlNjI2MmY1YjMwYWUwODJmNDkyYTNlNDM4NGIyNTUxNGQ3N2ZhNWJmMWM2ZmE0ZThlM2Q3ZWQ0Yjg1ZDUyMzc5MDY0ODBkZGYwODc0ODJjZDBmNDJhOWI5ODY4MzllZjRhNjM0MjAzODRjOWI4YjliY2IyMjM5ZmRjODEzOGUyYjVkMTdlMzA1OGUxMDNlNTdiNjA2YzkxZWM2NGMyMGYzZDRiZGRjMTRjZTFhYjFlZmZkZTI5YTgwN2JkNDMyY2FiMDA3YTA1MzI0YWVhMjIyMjViY2IxMzZmMGNlOGYxY2YzMTkwNTZmOTgzODM1M2E5Njk2Y2I4Mjg2YzU="
        // }
      }).then(function(res) {
      
        // var json = [ {
        //   "fileName" : "d33087332a6c477a806d823209fef5c7.png",
        //   "previewUrl" : null,
        //   "fileDisplayName" : "1511353597(1).png",
        //   "downloadUrl" : "/attachment/download?fid=402887dc630ba7e701630bb4fe8f0011&chksum=04c8e2fdbb7ec02bc3492f9c98fa8e36",
        //   "imageSmallerUrl" : "/attachment/dingding/201804/d33087332a6c477a806d823209fef5c7_sm.png",
        //   "imageMiddleUrl" : "/attachment/dingding/201804/d33087332a6c477a806d823209fef5c7_mid.png",
        //   "fileExt" : ".png",
        //   "delFlag" : "0",
        //   "fileModule" : null,
        //   "multiCorpId" : false,
        //   "previewDate" : null,
        //   "imediaUrl" : "/attachment/dingding/201804/d33087332a6c477a806d823209fef5c7.png",
        //   "fileSize" : 67577,
        //   "fileDisplayNameNoExt" : "1511353597(1)",
        //   "relativePath" : "dingding/201804",
        //   "isEncrypted" : 0,
        //   "imageUrl" : "/attachment/image?fid=402887dc630ba7e701630bb4fe8f0011&chksum=04c8e2fdbb7ec02bc3492f9c98fa8e36",
        //   "checksum" : "04c8e2fdbb7ec02bc3492f9c98fa8e36",
        //   "deleteUrl" : "/attachment/delete?fid=402887dc630ba7e701630bb4fe8f0011&chksum=ef9f55278b3594f3eaefef23feacaa7d",
        //   "id" : "402887dc630ba7e701630bb4fe8f0011",
        //   "contentType" : null
        // } ];
        // initList = initList.concat(json);
        // t.props.onChange(initList);
        if (res.ok) {
          res.json().then(function(obj) {
            initList = initList.concat(obj);
            t.props.onChange(initList);
            t.setState({
              initList:initList
            });
            // Get the JSON
          })
        } else if (res.status == 401) {
            // To do with res
        }
        }, function(e) {
            // Handling errors
        }).catch((error) => {
          console.log("错误："+error);
        });
           
    }
  }

  //加载文件列表

  render() {
    const t = this;
    return (
      <div className="">
        <div className={this.state.label==''?'t-DN':'t-field-box t-FBH t-FBAC t-FBJ'}>
          <div className={this.state.required?'t-field-layout-h-label t-FS16 required':'t-field-layout-h-label t-FS16'}>{this.props.label}</div>
        </div>
        <div className={t.state.uploadType=='image'?"t-FBH t-PL1 t-fw":"t-PL1 t-PR1"}>
        {t.state.initList.map((item, i) => {
            function calculate(no){
              let a = no/1024;
              if(a<1){
                return no+'B';
              }
              let b = a/1024;
              if(b<1){
                return Math.round(a*100)/100+'KB';
              }
              return Math.round(b*100)/100+'MB';
            }

            /*
            * 根据附件类型获取对应图标名称
            */
           function getIcon(fileExt){
            let fileIcon = ' iconfont icon-minus t-FC9 t-FL t-MR6';
            if(fileExt!=null){
              fileExt = fileExt.toLowerCase();
              if(typeof(fileExt)!='undefined' && fileExt!=''){
                if(fileExt=='.doc' || fileExt=='.docx'  ){
                  fileIcon = 'iconfont icon-DOC t-FC9 t-FL t-MR6 t-FS30 t-FCddblue ';
                }else if(fileExt=='.xls' || fileExt=='.xlsx'){
                  fileIcon = 'iconfont icon-XLS t-FC9 t-FL t-MR6 t-FS30 t-FCgreen';
                }else if(fileExt=='.ppt' || fileExt=='.pptx'){
                  fileIcon = 'iconfont icon-PPT t-FC9 t-FL t-MR6 t-FS30 t-FCorange';
                }else if(fileExt=='.pdf'){
                  fileIcon = 'iconfont icon-PDF t-FC9 t-FL t-MR6 t-FS30 t-FCred ';
                }else if(fileExt=='.jpg' || fileExt =='.jpeg'  || fileExt =='.bmp' ){
                  fileIcon = 'iconfont icon-JPG t-FC9 t-FL t-MR6 t-FS30 t-FCorange ';
                }else if(fileExt=='.zip'  || fileExt=='.gzip'){
                  fileIcon = 'iconfont icon-ZIP t-FC9 t-FL t-MR6 t-FS30 t-FCddblue ';
                }else if(fileExt=='.gif'){
                  fileIcon = 'iconfont icon-GIF t-FC9 t-FL t-MR6 t-FS30 t-FCgreen ';
                }else if(fileExt=='.mp4'){
                  fileIcon = 'iconfont icon-MP4 t-FC9 t-FL t-MR6 t-FS30 t-FCred';
                }else if(fileExt=='.txt'){
                  fileIcon = 'iconfont icon-TXT t-FC9 t-FL t-MR6 t-FS30 t-FCddblue';
                }else if(fileExt=='.wps'){
                  fileIcon = 'iconfont icon-WPS t-FC9 t-FL t-MR6 t-FS30 t-FCddblue';
                }else if(fileExt=='.png'){
                  fileIcon = 'iconfont icon-PNG t-FC9 t-FL t-MR6 t-FS30 t-FCgreen';
                }else if(fileExt=='.rar'){
                  fileIcon = 'iconfont icon-RAR t-FC9 t-FL t-MR6 t-FS30 t-FCgreen';
                }else{
                  fileIcon = 'iconfont icon-file2 t-FC9 t-FL t-MR6 t-FS30';
                }
              }
            } 
            return fileIcon;
          }
            
            return (
              t.state.uploadType=='image'?
                    <div className="dd-uploaded" key={i}>
                      <img width="60" height="60" src={t.state.urlPrev + item.id+'&token='+ t.state.token} />
                      <i className={t.state.canDel?'iconfont icon-minus':'t-DN'} onClick={this.del.bind(this, i)} ></i>
                    </div>
                  :
                  <div className="t-FBH" key={i}  >             
                    <div className="dd-border-e259 t-P10 t-MB10 t-FB1 t-BCf789" vAlign="center" onClick={this.view.bind(this, item)}>
                      <i className={getIcon(item.fileExt)}  ></i>
                      <div className="dd-t-list-text-content" >
                        <div className="t-FS14 t-omit t-LH1_4 t-FC3" >
                          {typeof(item.fileDisplayName)=='undefined'?item.name:item.fileDisplayName}
                        </div>
                        <div className="t-FS12 t-FBAC t-FCddfontblue-40 t-LH1_3" >{calculate(typeof(item.fileSize)=='undefined'?item.size:item.fileSize)}</div>
                      </div>
                    </div>
                    <i  className={t.state.canDel?'iconfont icon-minus dd-uploaded-delete':'t-DN'}  onClick={this.del.bind(this,i)}></i>
                  </div>
            );
          })}
          <div flex={1} className="t-PB1">
            <i id={'ddUploadPic' + t.state.keyNum} className={t.state.canAdd && (t.state.limitNo > t.props.initList.length || t.state.limitNo == -1) ? 'dd-add-btn iconfont icon-plus' : 't-DN'}></i>
          </div>
        </div>
      </div>

    );
  }
}

